package com.lxx.codegen.mbgplugins;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.internal.util.JavaBeansUtil;

public class SelectAllPlugin extends PluginAdapter{

	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}
	
	@Override
	public boolean clientGenerated(Interface interfaze,
			TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
//		Method m = new Method("query");
//		m.setVisibility(JavaVisibility.PUBLIC);
//		m.setReturnType(FullyQualifiedJavaType.getNewListInstance());
//		context.getCommentGenerator().addGeneralMethodComment(m,
//				introspectedTable);
//		interfaze.addMethod(m);
		return true;
	}
	
	@Override
	public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
		
		String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();//数据库表名
		List<IntrospectedColumn> columns = introspectedTable.getAllColumns();
		Pattern p = Pattern.compile("del_flag|delete_flag", Pattern.CASE_INSENSITIVE);
		String delFlag = null;
		for (IntrospectedColumn column : columns) {
			String propName = JavaBeansUtil.getCamelCaseString(column.getActualColumnName(), false);
			
			Matcher m = p.matcher(column.getActualColumnName());
			if (m.find()) {
				delFlag = propName;
			}
		}
		
		String whereStr = "";
		if (delFlag != null) {
			whereStr = " \\r\\n\\twhere "+delFlag+" = b'0'";
		}
		
		XmlElement parentElement = document.getRootElement();

		// 产生分页语句前半部分
		XmlElement queryElement = new XmlElement("select");
		queryElement.addAttribute(new Attribute("id", "query"));
		queryElement.addAttribute(new Attribute("resultMap", "BaseResultMap"));
		
		queryElement.addElement(
				new TextElement(
				"select <include refid=\"Base_Column_List\" /> from " + tableName + whereStr
				));
		
		parentElement.addElement(queryElement);

		return super.sqlMapDocumentGenerated(document, introspectedTable);
	}
	

}
